package com.copa.task;

import com.copa.entity.Games;
import com.copa.entity.GroupNumsConfig;
import com.copa.entity.News;
import com.copa.provider.games.GameTimeInfo;
import com.copa.provider.news.BaiduTopNews;
import com.copa.service.CommandService;
import com.copa.service.GamesService;
import com.copa.service.NewsService;
import com.copa.utils.MyCatCodeUtil;
import com.copa.utils.SimpleCalendarUtil;
import com.copa.utils.TimeUtil;
import love.forte.simbot.api.sender.BotSender;
import love.forte.simbot.bot.Bot;
import love.forte.simbot.bot.BotManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.copa.constant.Constants.GROUP_COMMAND;

/**
 * @author copa
 * @createDate 2022-02-22 16:29
 * @function 群聊定时任务
 */
@Component
public class GroupTask {

    @Autowired
    private BotManager manager;

    @Autowired
    private NewsService newsService;

    @Autowired
    private BaiduTopNews baiduTopNews;

    @Autowired
    private CommandService commandService;

    @Resource
    private GameTimeInfo gameTimeInfo;

    @Resource
    private GroupNumsConfig groupNumsConfig;

    @Resource
    private GamesService gamesService;

//    @Value("${group.num}")
//    private List<String> groupNums;

    /**
     * 每天0时在群里报晚安~
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void sleepToGroup() {
        List<String> groupNums = groupNumsConfig.getNumList();
        Bot bot = manager.getDefaultBot();
        BotSender sender = bot.getSender();
        for (String groupNum : groupNums) {
            sender.SENDER.sendGroupMsg(groupNum,
                    commandService.findCommandByCommandAndType("定时0", GROUP_COMMAND));
        }
    }

    /**
     * 每天0时在群里报节日快乐吖~
     */
    @Scheduled(cron = "10 0 0 * * ?")
    public void wishToGroup() {
        List<String> groupNums = groupNumsConfig.getNumList();
        Bot bot = manager.getDefaultBot();
        BotSender sender = bot.getSender();
        try {
            DateTimeFormatter dateTimeFormatter = TimeUtil.toTimeFormat("yyyy-MM-dd");
            String lunarFestival = SimpleCalendarUtil.getCalendarDetail(LocalDate.now().format(dateTimeFormatter), "yyyy-MM-dd")
                    .getLunarFestival();
            String solarFestival = SimpleCalendarUtil.getCalendarDetail(LocalDate.now().format(dateTimeFormatter), "yyyy-MM-dd")
                    .getSolarFestival();
            for (String groupNum : groupNums) {
                if (!"".equals(lunarFestival)) {
                    if ("端午节".equals(lunarFestival)) {
                        sender.SENDER.sendGroupMsg(groupNum, "今天是" + lunarFestival + "，up（copa）在这里祝亲们端午安康~");
                        return;
                    }
                    sender.SENDER.sendGroupMsg(groupNum, "今天是" + lunarFestival + "，up（copa）在这里祝亲们节日快乐吖~(>^ω^<)");
                } else if (!"".equals(solarFestival)){
                    sender.SENDER.sendGroupMsg(groupNum, "今天是" + solarFestival + "，up（copa）在这里祝亲们节日快乐吖~(>^ω^<)");
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 每天7时在群里报早安~
     */
    @Scheduled(cron = "0 0 7 * * ?")
    public void wakeUpToGroup() {
        List<String> groupNums = groupNumsConfig.getNumList();
        Bot bot = manager.getDefaultBot();
        BotSender sender = bot.getSender();
        for (String groupNum : groupNums) {
            sender.SENDER.sendGroupMsg(groupNum,
                    commandService.findCommandByCommandAndType("定时7", GROUP_COMMAND));
        }
    }

    /**
     * 每天6时在爬百度热搜~
     */
    @Scheduled(cron = "0 0 6 * * ?")
    public void getBaiduHotNews() {
        baiduTopNews.getNews();
    }

    /**
     * 每天0时在爬游戏时光~
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void getGameInfo() {
        gameTimeInfo.getGamesInfo();
    }

    // TODO:群友反映：发新闻以为是发广告，所以这个暂时废弃
    /**
     * 每天7时01分在群里发新闻~
     */
//    @Scheduled(cron = "0 1 7 * * ?")
//    public void newsToGroup() throws InterruptedException {
//        Bot bot = manager.getDefaultBot();
//        BotSender sender = bot.getSender();
//        String time = LocalDate.now().format(TimeUtil.toTimeFormat("yyyy-MM-dd"));
//        List<News> contentList = newsService.getDayNews();
//        List<String> tempList =  new ArrayList<>(20);
//        for (String groupNum : groupNums) {
//            sender.SENDER.sendGroupMsg(groupNum, "以下是" + time + "的热搜榜");
//            Thread.sleep(1000);
//            int i = 0;
//            int j = 0;
//            for (News news : contentList) {
//                i++;
//                String content = news.getTopNum() + "." + news.getTitle()
//                        //+ " " + news.getHotNum()
//                        + "\n" + news.getHref();
//                tempList.add(content);
//                if (i % 5 == 0) {
//                    j++;
//                    // 群友抱怨：加了这个不能点开链接（手机端点不了）
//                    //String message = MyCatCodeUtil.getNews(String.join("\n------------------------------\n", tempList));
//                    String message = MyCatCodeUtil.getNews(String.join(" \n", tempList));
//                    sender.SENDER.sendGroupMsg(groupNum, message);
//                    tempList.clear();
//                    if (j == 4) {
//                        break;
//                    }
//                    Thread.sleep(1000);
//                }
//            }
//            Thread.sleep(1000);
//            sender.SENDER.sendGroupMsg(groupNum, "推送完毕~以上是" + time + "的热搜榜，数据来源于百度热搜榜~");
//        }
//    }

    /**
     * 每天0时5分在群里发游戏内容~
     */
    @Scheduled(cron = "0 5 0 * * ?")
    public void newsToGroup() throws InterruptedException {
        Bot bot = manager.getDefaultBot();
        BotSender sender = bot.getSender();
        String time = LocalDate.now().format(TimeUtil.toTimeFormat("yyyy-MM-dd"));
        List<Games> contentList = gamesService.findBySaleTime(time);
        List<String> groupNums = groupNumsConfig.getNumList();
        for (String groupNum : groupNums) {
            if (Objects.isNull(contentList) || contentList.isEmpty()) {
                sender.SENDER.sendGroupMsg(groupNum, "今天是" + time + "，暂时无发售游戏内容噢~敬请期待~大家洗洗睡吧~");
                continue;
            }
            List<String> contentTempList = new ArrayList<>();
            sender.SENDER.sendGroupMsg(groupNum, "以下是" + time + "的发售游戏内容");
            TimeUnit.SECONDS.sleep(1);
            for (Games games : contentList) {
                String content = "游戏名称：" + games.getChiName() + "(" + games.getOtherName() + ")\n" +
                        "游戏图片链接：" + games.getImgUrl() + "\n" +
                        "游戏平台：" + games.getPlatform() + "\n" +
                        "游戏基因：" + games.getGameGene() + "\n" +
                        "发售时间：" + games.getSaleTime();
                contentTempList.add(content);
            }

            String message = MyCatCodeUtil.getNews(String.join("\n---------------\n", contentTempList));
            sender.SENDER.sendGroupMsg(groupNum, message);
            TimeUnit.SECONDS.sleep(1);
            sender.SENDER.sendGroupMsg(groupNum, "推送完毕~以上是" + time + "的发售游戏内容，以上内容来源于游戏时光~");
        }
    }


}
